package com.unity.bh3.interceptor;

import com.unity.bh3.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 用户认证拦截器
 * 用于验证用户身份并注入userId到请求属性中
 */
@Slf4j
@Component
public class UserAuthInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("请求的URL: {}", request.getRequestURI());
        String userIdHeader = request.getHeader("User-Id");
        
        if (userIdHeader == null || userIdHeader.trim().isEmpty()) {
            log.warn("请求缺少User-Id头: {}", request.getRequestURI());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"msg\":\"缺少用户身份信息\",\"data\":null}");
            return false;
        }
        
        try {
            Long userId = Long.valueOf(userIdHeader);
            
            // 验证用户是否存在
            if (userService.getUserInfo(userId) == null) {
                log.warn("用户不存在: {}", userId);
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write("{\"code\":401,\"msg\":\"用户不存在\",\"data\":null}");
                return false;
            }
            
            // 将用户ID设置到请求属性中，供Controller使用
            request.setAttribute("userId", userId);
            log.debug("用户认证成功: userId={}, uri={}", userId, request.getRequestURI());
            
            return true;
            
        } catch (NumberFormatException e) {
            log.warn("User-Id格式错误: {}", userIdHeader);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":400,\"msg\":\"用户ID格式错误\",\"data\":null}");
            return false;
        } catch (Exception e) {
            log.error("用户认证过程中发生错误: ", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":500,\"msg\":\"服务器内部错误\",\"data\":null}");
            return false;
        }
    }
}